package Controller.Music;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import utility.Paging;

import Bean.JoinBean;
import Bean.MusicBean;
import Bean.rowBean;
import Dao.MusicDao;

public class searchMusicController implements Controller{
	private MusicDao dao;
	Paging pageInfo = null;
	public void setDao(MusicDao dao){
		this.dao = dao;
	}
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse arg1) throws Exception {
		String pageNumber = request.getParameter("pageNumber");
		String pageSize = request.getParameter("pageSize");
		
		String keyword = request.getParameter("keyword");
		String search = request.getParameter("searchSelect");
		System.out.println(keyword+"검색어 "+search+" 종류");
		
		String url = "";
		String contextPath = request.getContextPath();
		System.out.println(contextPath);
		
		url = contextPath + "/search.music";
		
		int totalCount = 0;
		if(search.equals("search_music")){
			totalCount = dao.searchMusicTotal(keyword);
		}else if(search.equals("search_singer")){
			totalCount = dao.searchSingerTotal(keyword);
		}
		String param = "?keyword="+keyword+"&searchSelect="+search;
		pageInfo = new Paging(pageNumber, pageSize, totalCount, url, param);
		
		rowBean row = new rowBean();
		row.setKeyword(keyword);
		row.setBeginRow(pageInfo.getBeginRow());
		row.setEndRow(pageInfo.getEndRow());
		
		
		List<JoinBean> newList = null;
		if(search.equals("search_music")){
			newList = dao.searchMusicList(row);
			
		}else if(search.equals("search_singer")){
			newList = dao.searchSingerList(row);
		}
		
		ModelAndView mav = new ModelAndView();
		
		for (JoinBean joinBean : newList) {
			MusicBean musicBean = joinBean.getMusicBean();
			if(joinBean.getMusicBean().getMs_featuring().equals("없음")){
				musicBean.setMs_featuring("");
				joinBean.setMusicBean(musicBean);
			}else{
				musicBean.setMs_featuring("(feat."+musicBean.getMs_featuring()+")");
				joinBean.setMusicBean(musicBean);
			}
		}
		
		String title = "에 대한 검색 결과";
		mav.setViewName("musicList");
		mav.addObject("newList", newList);
		mav.addObject("title", title);
		mav.addObject("keyword", keyword);
		mav.addObject("pageInfo", pageInfo);
		
		
		return mav;
	}
}
